﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.IO;
using System.Text;

public partial class Admin_bkgl : System.Web.UI.Page
{
    DataClassesDataContext db1 = new DataClassesDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack == true)
        {
            BindData();
            string IP = Request.ServerVariables.Get("Remote_Addr").ToString();
            string nowtime = DateTime.Now.ToString();
            DateTime nowtime1 = Convert.ToDateTime(nowtime);
            int nowusername = Convert.ToInt32(Session["username"]);
            var newrizhi = new rizhi
            {
                userName = nowusername,
                time = nowtime1,
                ip = IP,
                caozuo = "进入报名信息管理"
            };
            db1.rizhi.InsertOnSubmit(newrizhi);
            db1.SubmitChanges();
        }
    }
    private void BindData()
    {
        var result = (from p in db1.proc_GetBkgxNowYear()
                      select p).ToList().First();
        string ZcYear = result.dYear;
        var resultStu = (from p in db1.proc_GetStuInfo()
                         where p.bkyear == ZcYear && p.proflag > 0 && p.wbh.Contains(TextBox1.Text) || p.sname.Contains(TextBox1.Text) || p.proNum.Contains(TextBox1.Text)
                         select p).ToList();
        GridView2.DataSource = resultStu;
        GridView2.DataBind();
    }
    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl = (Label)e.Row.Cells[0].FindControl("Label2");
            lbl.Text = (GridView2.PageIndex * GridView2.PageSize + e.Row.RowIndex + 1).ToString();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        BindData();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        /*var result = (from p in db1.proc_GetBkgxNowYear()
                      select p).ToList().First();
        string ZcYear = result.dYear;
        var resultStu = (from p in db1.proc_GetStuInfo()
                         where p.bkyear == ZcYear && p.proflag > 0 && p.wbh.Contains(TextBox1.Text) || p.sname.Contains(TextBox1.Text) || p.proNum.Contains(TextBox1.Text)
                         select p).ToList();
        string FileAndTitleName = result.schoolName + ZcYear + "年“专升本”学生报名信息表";
        GridView2.DataSource = resultStu;
        GridView2.DataBind();
        string filePath = Server.MapPath("../ExcelTemplet/Temp/" + Guid.NewGuid().ToString() + ".xls");
        File.Copy(Server.MapPath("../ExcelTemplet/StuApplyInfo.xls"), filePath);
        // 使用OleDb驱动程序连接到副本
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0;");
        using (conn)
        {
            conn.Open();
            // 增加记录
            foreach (var item in resultStu)
            {
                StringBuilder sql = new StringBuilder();
                sql.Append("INSERT INTO [Sheet1$]([网报号],[姓名],[报考专业],[毕业院校],[毕业专业],[手机号],[身份证],[状态]) VALUES('").Append(item.wbh).Append("','").Append(item.sname).Append("','").Append(item.proName).Append("','").Append(item.sdept).Append("','").Append(item.byzy).Append("','").Append(item.sphone).Append("','").Append(item.sidfy).Append("','").Append(item.status).Append("')");
                OleDbCommand cmd = new OleDbCommand(sql.ToString(), conn);
                cmd.ExecuteNonQuery();
            }
        }
        // 输出副本的二进制字节流
        Response.ContentType = "application/ms-excel";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileAndTitleName + ".xls");
        Response.BinaryWrite(File.ReadAllBytes(filePath));
        // 删除副本
        File.Delete(filePath);
        //excl导出
        /*Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=ExcelFile.xls");
        //设定输出的字符集
        Response.Charset = "gb2312";
        //设置输出文件类型为excel文件
        Response.ContentType = "application/ms.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView2.AllowPaging = false;
        GridView2.RenderControl(htmlWrite);
        //把HTML写回浏览器
        Response.Write(stringWrite.ToString());
        Response.End(); */
        GridView2.AllowPaging = false;
        //撤销分页后绑定所有数据
        BindData();
        //导出到Excel
        string style = @"<style> .text { mso-number-format:\@; } </script> ";
        Response.ClearContent();
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
        Response.ContentType = "application/excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView2.RenderControl(htw);
        Response.Write(style);
        Response.Write(sw.ToString());
        Response.End();
        //导出后恢复分页
        GridView2.AllowPaging = true;
        //重新绑定
        BindData();

    }

    protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        // 得到该控件
        GridView theGrid = sender as GridView;
        int newPageIndex = 0;
        if (e.NewPageIndex == -3)
        {
            //点击了Go按钮
            TextBox txtNewPageIndex = null;

            //GridView较DataGrid提供了更多的API，获取分页块可以使用BottomPagerRow 或者TopPagerRow，当然还增加了HeaderRow和FooterRow
            GridViewRow pagerRow = theGrid.BottomPagerRow;

            if (pagerRow != null)
            {
                //得到text控件
                txtNewPageIndex = pagerRow.FindControl("txtNewPageIndex") as TextBox;
            }
            if (txtNewPageIndex != null)
            {
                //得到索引
                newPageIndex = int.Parse(txtNewPageIndex.Text) - 1;
            }
        }
        else
        {
            //点击了其他的按钮
            newPageIndex = e.NewPageIndex;
        }
        //防止新索引溢出
        newPageIndex = newPageIndex < 0 ? 0 : newPageIndex;
        newPageIndex = newPageIndex >= theGrid.PageCount ? theGrid.PageCount - 1 : newPageIndex;

        //得到新的值
        theGrid.PageIndex = newPageIndex;
        BindData();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm control is rendered for
        //为了保险期间还可以在这里加入判断条件防止HTML中已经存在该ID
    }
}